<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {

	public function __construct() {
        parent::__construct();
        $this->_color();
    }

    /**
     * 初始化
     * @return
     */
    private function _color() {
        
        $color = M('color_config')->where('id=1')->find();
        $this->assign('color',$color);
    }
	//首页
	public function index(){
		$tui_id = session('tui_id') ? session('tui_id') : '0';
		$a_id = session('a_id') ? session('a_id') : '0';

		if (!session('uid.id'))
		{
            $this->redirect('Index/user_login');
		}

		$id = session('uid.id');
		$user = M('user')->where("id=$id")->find();
		if (!$user) {
			$this->redirect("Index/user_login");
		}
		if (!$user['openid']) {
			$this->redirect("Index/weixin");
		}
		
		if ($a_id>0) {
			$url = 'http://'.C('INT_COM').'/index.php/Home/Index/activity?a_id='.$a_id;

			if ($_SERVER['SERVER_NAME'] != C('INT_COM')) 
			{
				$url = 'http://'.$_SERVER['SERVER_NAME'].'/next/index.php/Home/Index/activity?cate_id='.$a_id;
			}
			header("Location: $url");
		}
		if (!session('weixin')) 
		{
			$weixin = M('weixin')->order('id desc')->find();
			session('wxconfig',$weixin);
		}

		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		
		$this->assign('data',$data);

		$this->display();
	}
	public function index_old(){
		$this->display();
	}
	//活动详情页
	public function activity(){
		// is_login();
		$id = session('uid.id');
		if (!$id) 
		{
			$this->redirect("Index/weixin");
		}
		$a_id = I('get.cate_id');
		$user_id = get_user();
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');

		$name = M('user')->where(array('id'=>$user_id))->getField('username');
		$title = M('activity')->where("id=$a_id")->field('title,site,start_time')->find();
		$title['start_time'] = date('Y-m-d H:i:s',$title['start_time']);
		$data['title']=$title['title'];

		$data['desc']='《 Next 》'.$name.'邀请您于'.$title['start_time'].'在'.$title['site'].'参加ta的活动！';

		$data['link']="http://".C("INT_COM")."/index.php/Home/Index/weixin?tui_id=$user_id&a_id=$a_id";
		
		$url=M('config_img')->where('id=1')->getField('image');

		$data['imgurl'] ="http://".C("INT_COM")."/".$url;
		// dump($data);exit();
        $this->assign('data',$data);
		$this->display();
	}
	//位置
	public function position(){
		is_login();
		$this->display();
	}
	//玩伴
	public function playmate(){
		// is_login();
		$id = session('uid.id');
		if (!$id) 
		{
			$this->redirect("Index/weixin");
		}
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		$data['self_id'] = $id;
		// dump($data);exit();
		$this->assign('data',$data);
		$this->display();
	}
	//消息
	public function news(){
		// A('Admin/Fivemin')->index();
		is_login();
		$this->display();
	}
	//我
	public function me(){
		is_login();
		$this->display();
	}
	//分享
	public function share(){
		is_login();
		$this->display();
	}
	//我的钱包
	public function purse(){
		is_login();
		$this->display();
	}
	//验证
	public function identify(){
		$this->display();
	}
	//提现
	public function withdraw(){
		is_login();
		$this->display();
	}

	// 活动模块
	// 附近的活动列表
	public function activity_list_map() {
		is_login();
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		
		$this->assign('data',$data);
		$this->display();
	}
	// 活动列表
	public function activity_list() {
		is_login();
		$this->display();
	}
	// 活动地图
	public function activity_map() {
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		
		$this->assign('data',$data);
		$this->display();
	}
	// 活动聊天
	public function activity_chat() {
		is_login();
		$user_id = get_user();
		$rong_id = M('user')->where(array('id'=>$user_id))->getField('rong_id');
		if (!$rong_id) {
			$rong_id=get_rong_token($user_id);
			M('user')->where(array('id'=>$user_id))->save(array('rong_id'=>$rong_id));
		}
		$appkey = get_tong_AppKey();
		$this->assign("appkey", $appkey);
		$this->assign("rong_id", $rong_id);
		$this->display();
	}
	// 活动刷脸到达
	public function activity_scan() {
		is_login();
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		
		$this->assign('data',$data);
		$this->display();
	}
	// 活动评价
	public function activity_evaluation() {
		is_login();
		$this->display();
	}

	public function info1(){
		$this->display();
	}
	// 发起活动
	// 活动首页
	public function invite() {
		is_login();
		$this->display();
	}
	// 活动主题
	public function invite_title() {
		is_login();
		$this->display();
	}
	// 活动地图
	public function invite_map() {
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		
		$this->assign('data',$data);
		$this->display();
	}
	// 活动谁可以看
	public function invite_permission() {
		$this->display();
	}
	// 活动联系人
	public function invite_contact() {
		$this->display();
	}
	// 活动联系人选择
	public function invite_choose_contact() {
		$this->display();
	}
	// 活动帮助
	public function invite_help() {
		$this->display();
	}
	// 活动收银台
	public function invite_cash() {
		is_login();
		$this->display();
	}

	// 查看个人资料
	// 个人信息首页
	public function user() {
		is_login();
		$this->display();
	}
	// 个人信息活动页
	public function user_activity() {
		is_login();
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		
		$this->assign('data',$data);
		$this->display();
	}
	// 个人信息我要认证
	public function user_identify() {
		// is_login();
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		$this->assign('data',$data);
		$this->display();
	}
	// 个人信息钱包
	public function user_wallet() {
		is_login();
		$this->display();
	}
	// 个人信息设置提现
	public function user_withdraw() {
		is_login();
		$this->display();
	}
	// 个人信息设置提现密码
	public function user_password() {
		is_login();
		$this->display();
	}
	// 个人信息设置提现密码验证
	public function user_verifypw() {
		is_login();
		$this->display();
	}
	// 个人信息设置修改提现密码
	public function user_pwmodify() {
		is_login();
		$this->display();
	}
	// 个人信息设置忘记密码
	public function user_forgetpw() {
		is_login();
		$this->display();
	}
	// 个人信息提现记录
	public function user_record() {
		is_login();
		$this->display();
	}
	// 个人信息红包
	public function user_hongbao() {
		is_login();
		$this->display();
	}
	// 个人信息认证
	public function user_identity() {
		is_login();
		$this->display();
	}
	// 个人资料首页
	public function user_detail() {
		// is_login();
		$id = session('uid.id');
		if (!$id) 
		{
			$this->redirect("Index/weixin");
		}
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');

		$data['imgurl'] = "http://".C("INT_COM").M('config_img')->where('id=2')->getField('image');

		$this->assign('data',$data);
		$this->display();
	}
	// 个人资料用户名
	public function user_name() {
		is_login();
		$this->display();
	}
	// 个人资料签名
	public function user_intro() {
		is_login();
		$this->display();
	}
	// 个人资料形体
	public function user_body() {
		is_login();
		$this->display();
	}
	// 个人资料相册
	public function user_album() {
		is_login();
		$this->display();
	}
	// 个人资料修改头像
	public function user_header() {
		// is_login();
		$userinfo = session('uid.id');
		if (!$userinfo) 
		{	
			// $url = 'http://'.C('INT_COM').'/index.php/Home/Index/user_login';
			// header("Location: $url");
            $this->redirect('Index/user_login');
		}
		$this->display();
	}
	// 个人资料举报
	public function user_report() {
		is_login();
		$this->display();
	}
	// 登录
	public function user_login() {

		// A('Admin/Fivemin')->index();
		$tui_id = I('get.id');
		$a_id = I('get.a_id');
		session('tui_id',$tui_id);
		session('a_id',$a_id);
		$this->redirect("Index/weixin");
		if($tui_id){
			$this->assign('tui_id',$tui_id);
		}
		if($a_id){
			$this->assign('a_id',$a_id);
		}
		$this->display();
	}
	// 账号与安全
	public function user_security() {
		$this->display();
	}
	// 修改手机号
	public function user_phone() {
		is_login();
		$this->display();
	}
	// 分享
	public function user_share() {
		$this->display();
	}
	// 我的二维码
	public function user_code() {
		is_login();
		$user_id = get_user();

		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');

		$name = M('user')->where(array('id'=>$user_id))->getField('username');
		$data['title']='Next-'.$name.'邀请你加入我们';
		$data['desc']='Next-'.$name.'邀请你加入我们';

		$data['link']="http://".C("INT_COM")."/index.php/Home/Index/user_login?id=".$user_id;
		
		$url=M('config_img')->where('id=4')->getField('image');

		$data['imgurl'] ="http://".C("INT_COM")."/".$url;
		$data['beijing_url'] = "http://".C("INT_COM").M('config_img')->where('id=3')->getField('image');

        $this->assign('data',$data);
		$this->display();
	}
	// weixin jssdk
	public function jssdk(){
		// 融云的id
		$user_id = get_user();
		$rong_id = M('user')->where(array('id'=>$user_id))->getField('rong_id');
		if (!$rong_id) {
			$rong_id=get_rong_token($user_id);
			M('user')->where(array('id'=>$user_id))->save(array('rong_id'=>$rong_id));
		}
		$appkey = get_tong_AppKey();
		$data['rong_appkey'] =$appkey;
		$data['rong_id'] =$rong_id;

		// 微信的 四个参数
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');

		$data['news'] = M('message')->where("(status=0 AND shou_id=$user_id)")->count();
		$this->ajaxReturn($data);
	}
	// 我推荐的玩伴
	public function user_playmate() {
		is_login();
		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');
		
		$this->assign('data',$data);
		$this->display();
	}
	// 我的共享红包
	public function user_share_hongbao() {
		is_login();
		$this->display();
	}
	// 关于
	public function user_about() {
		$this->display();
	}

	public function login_out() {
        session(null);
        $this->redirect('Index/user_login');
    }
	public function weixin(){
		$tui_id = I('get.tui_id') ? I('get.tui_id') : 0;
		$user_id = session('tui_id') ? session('tui_id') : $tui_id;
		$a_id = I('get.a_id')?I('get.a_id'):0;
        $appid=C('APP_ID');
        $redirect_uri = urlencode('http://'.C('INT_COM').'/index.php/Home/Index/openid?a_id='.$a_id);
        Header("Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=".$user_id."#wechat_redirect");
    } 
	/** 
	 * 微信登陆
	 * @return code 微信code
	 * @return openid 微信openid
	 */
	public function openid(){
        $code=I('get.code');
        $state=I('get.state');
        $a_id = I('get.a_id');
        $appid=C('APP_ID');
        $secret=C('app_secret');
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code={$code}&grant_type=authorization_code";

        $res=$this->curlGet($url,$type="GET");
        $json=json_decode($res, true);

        $url_info = "https://api.weixin.qq.com/sns/userinfo?access_token=".$json['access_token']."&openid=".$json['openid']."&lang=zh_CN";
        $result=$this->curlGet($url_info,$type="GET");
     
        $userinfo=json_decode($result, true);
        
        session('openid',$userinfo['openid']);
        session('userinfo',$userinfo);
        
        $MODEL = M("User");
        $map['openid']=$userinfo['openid'];
        $data=$MODEL->where($map)->find();
        
        if($data['username']){ 
        	$this->sendoutlogin($data['id']);
        	$MODEL->where($map)->save(array('login_time'=>time()));
            session('uid',$data);
            if ($a_id>0)
            {
            	$urls = 'http://'.C('INT_COM').'/index.php/Home/Index/activity?cate_id='.$a_id;
            	header("Location: $urls");
            	// $this->redirect("Index/activity",array('cate_id'=>$a_id));
            }else{ 
            	$this->redirect("Index/index");
            }
        }else{
        	$first_str = _getFirstCharter(session('userinfo.nickname'));
        	if (!$first_str) {
        		$first_str = _getFirstCharter(substr(session('userinfo.nickname') , 0 , 3));
        		if(!$first_str)
        			$first_str = '#';
        	}

            $name = session('userinfo.nickname');
            $name = preg_replace('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', '', $name);
            $name = preg_replace('/xE0[x80-x9F][x80-xBF]‘.‘|xED[xA0-xBF][x80-xBF]/S','?', $name);
            $name = json_decode(preg_replace("#(\\\ud[0-9a-f]{3})#ie","",json_encode($name)));
           
        	$list = array(
                'openid'=>session('openid'),
                'username'=>$name,
                // 'photo_id'=>session('userinfo.headimgurl'),
                'city'	=> session('userinfo.city'),
                'add_time' => time(),
                'login_time' => time(),
                'first_str'  => $first_str,
                'tui_id' => $state,
            );

            $is_uid = session('userid');// 判断是不是第一次手机注册
            if ($is_uid) 
            {	
            	//如果有is_uid 说明是手机注册了后
            	M('user')->where(array('id'=>$is_uid))->save($list);
            	$this->redirect("Index/index");
            	$user_id = $is_uid;
            }
            // else{
            // 	$user_id = M('user')->add($list);// 第一次微信注册
            // }
            
            $is_login = session('userids');
            // dump($is_login);exit();
            if ($is_login) {
            	//如果有userids 说明是手机号登录的但是没有openid,要获取到openid后绑定openid，
            	M('user')->where(array('id'=>$is_login))->save($list);
            	$this->redirect("Index/index");
            }

            // 第一次微信注册
            if(empty($list['username'])){
            	return false;
            }
        	$user_id = M('user')->add($list);
            $list['id'] = $user_id;
            session('uid',$list);

            $content = '欢迎注册。next';
            $mess = array(
                'fa_id'  => '0',
                'shou_id'=>$user_id,
                'add_time'=>time(),
                'type'   => '0',
                'content'=> $content,
                'interval'=>intval(time()/300),
                );
            M('message')->add($mess);
            M('message_list')->add(array('fa_id'=>'0','shou_id'=>$user_id,'news'=>$content,'add_time'=>time()));
            system_to_one($user_id,$content);
            $this->redirect("Index/index");
            $urls = 'http://'.C('INT_COM').'/index.php/Home/Index/user_forget?type=complete&a_id='.$a_id.'&tui_id='.$user_id;
            header("Location: $urls");
            // $this->redirect("Index/user_forget",array('type'=>'complete','a_id'=>$a_id));
        }
    }
    
    public function gettoken(){
        //   	if (session('wxtoken')) {
		// 	return session('wxtoken');
		// }
    	$appid=C('APP_ID');
        $secret=C('app_secret');
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res=$this->curlGet($url,$type="GET");
        $json=json_decode($res, true);
        session('wxtoken',$json['access_token']);
        return $json['access_token'];
    }
    public function getjsticket(){
	    $access_token = $this->gettoken();
	    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi"; // 两小时有效
	    $rurl = $this->curlGet($url);
	    $rurl = json_decode($rurl,true);
	    if($rurl['errcode'] != 0){
	      return false;
	    }else{
	      $jsticket = $rurl['ticket'];
	      return $jsticket;
	    }
	}
	public function getsignature(){
		// if (session('signature')) {
		// 	return session('signature');
		// }
	    $noncestr = 'sdsdsdssd';
	    $jsapi_ticket = $this->getjsticket();
	    $timestamp = time();
	    $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	    $string1 = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$noncestr.'&timestamp='.$timestamp.'&url='.$url;
	    $signature = sha1($string1);
	    session('signature',$signature);
	    return $signature;
	}
	public function info(){

		$data['signature']=$this->getsignature();
		$data['timestamp']=time();
		$data['nonceStr']='sdsdsdssd';
		$data['appId']=C('APP_ID');

        $this->assign('data',$data);
		$this->display();
	}
	// 给微信公众号发送消息 测试
	public function message(){
		$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$this->gettoken();
		// $data = array(
		//  	"touser"  => 'o07mys-gbf6Ubqxr5Epkh-gj6Aac',
		//     "msgtype" => "text",
		//     "text"    =>array('content'=>'123'),
		// 	);
		$data['touser']='oR_ADwGqA8nnBWwOvaClTJBqFGlo';
		$data['msgtype'] = 'text';
		$data['text'] = array('content'=>'试试');
		$data = $this->ch_json_encode($data);
		$rurl = curlGet($url,$data);
	    $rurl = json_decode($rurl,true);
	    dump($url);
	    dump($rurl);exit();
	}
	// 给微信公众号发送消息 正式使用的
	public function wx_mb_message($user_openid,$content){
		$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$this->gettoken();

		$data['touser']=$user_openid;
		$data['msgtype'] = 'text';
		$data['text'] = array('content'=>$content);
		$data = $this->ch_json_encode($data);
		$rurl = curlGet($url,$data);
	    $rurl = json_decode($rurl,true);
	}

	// 给微信公众号发送模板消息 
	public function wx_message($user_openid,$content){
		$url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->gettoken();
		
		$data['touser']= $user_openid;//'oR_ADwGqA8nnBWwOvaClTJBqFGlo';//$user_openid;
		$data['template_id'] = 'o0ZttcurRDcCKJDXG5st0OaE0cC-ihhRi8myW_4jeQs';
		$data['url'] = 'http://www.next.zm-idea.com/index.php/Home/Index/news.html';
		// $data['url'] = 'http://www.next.zm-idea.com/index.php/Home/Index/index.html';
		$data['data'] = array(
			// 'content'=>$content
			'first'=>array(
				'value'=>'亲爱的用户，'.$content,
				"color"=>"#173177"
				),
			'Good'=>array(
				'value'=>'个人信息',
				"color"=>"#173177"
				),
			'contentType'=>array(
				'value'=>'待查看', //$content,
				"color"=>"#173177"
				),
			'remark'=>array(
				'value'=>'点击查看详情！',
				"color"=>"#173177"
				),
			);
		$data = $this->ch_json_encode($data);
		$rurl = curlGet($url,$data);
	    $rurl = json_decode($rurl,true);
	    // return $rurl;
	    // dump($rurl);
	}
	// 解决 json_decode 不能中文
	public function ch_json_encode($data) {
   
	    function ch_urlencode($data) {
	       if (is_array($data) || is_object($data)) {
	           foreach ($data as $k => $v) {
	               if (is_scalar($v)) {
	                   if (is_array($data)) {
	                       $data[$k] = urlencode($v);
	                   } else if (is_object($data)) {
	                       $data->$k = urlencode($v);
	                   }
	               } else if (is_array($data)) {
	                   $data[$k] = ch_urlencode($v); //递归调用该函数
	               } else if (is_object($data)) {
	                   $data->$k = ch_urlencode($v);
	               }
	           }
	       }
	       return $data;
	   }
	   
	   $ret = ch_urlencode($data);
	   $ret = json_encode($ret);
	   return urldecode($ret);
	}

	// 如果有在线 挤掉
	public function sendoutlogin($user_id){
		$status = get_rong_status($user_id);
		
		if ($status == 1) {
			$user_id = $user_id;
			$content = '79858';

			$data = system_to_one($user_id,$content,$extra);
		}

		return true;
		
	}
	// 支付
	public function pay(){
		if (!session('weixin')) 
		{
			$weixin = M('weixin')->order('id desc')->find();
			session('wxconfig',$weixin);
		}
		
        $order['user_id'] = get_user();
        $order['deal_num'] = time();
        $order['moneys'] = 1;
        Vendor('WxpayV3.WxPayPubHelper');
        $tools = new \JsApiPay();
        // $this->ajaxReturn($tools);
        //①、获取用户openid

        // // $openId = $tools->GetOpenid();
        // $openId =session("openid");
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("平台");
        $input->SetAttach($order['user_id']);
        $input->SetOut_trade_no($order['deal_num']);
        $input->SetTotal_fee($order['moneys']);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("用户付款");
        $input->SetNotify_url("http://".C("INT_COM")."/index.php/Home/System/Wx_pay_ajax_oks");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid('oR_ADwGqA8nnBWwOvaClTJBqFGlo');

        $wxorder = \WxPayApi::unifiedOrder($input);
		// $this->ajaxReturn($wxorder);
        $jsApiParameters = $tools->GetJsApiParameters($wxorder);
        // $this->ajaxReturn($jsApiParameters);
        $res["code"]=100;
        $res["data"]=$jsApiParameters;
        $this->ajaxReturn($res);
    }
    function curlGet($url,$type="GET"){
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $type);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $temp = curl_exec($ch);
        curl_close($ch);
        return $temp;
    }
}